﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Client.App.Services
{
    public abstract class BaseStatisticsService<T> : IStatisticsService<T>
    {
        #region Fields

        private readonly Func<T> _func;
        private readonly int _attempts;
        private IEnumerable<T> _results;

        #endregion

        #region Properties

        public Func<T> Func
        {
            get { return _func; }
        }

        public int Attempts
        {
            get { return _attempts; }
        }

        protected IEnumerable<T> Results
        {
            get { return _results ?? (_results = GetResults()); }
        }
        
        #endregion

        #region Constructors

        protected BaseStatisticsService(Func<T> func, int attempts)
        {
            if (ReferenceEquals(func, null))
            {
                throw new ArgumentNullException("func");
            }
            _func = func;
            _attempts = attempts;
        }

        #endregion

        #region Methods

        protected virtual IEnumerable<T> GetResults()
        {
            for (int i = 0; i < _attempts; ++i)
            {
                yield return _func();
            }
        }
        
        public virtual T GetAverage()
        {
            return this.GetAverage(Results);
        }

        public abstract T GetAverage(IEnumerable<T> values);


        #endregion
    }
}
